(function(angular) {
	"use strict";
	angular.module("fs.waf").controller("cls.amendment.logController", logController);
	logController.$inject = [ "$q", "$scope", "modalService", "gridService", "layoutConfig", "validatorConfig", "authService", "arithService", "amendmentService", "dateService", "formatService" ];
	function logController($q, $scope, modalService, gridService, layoutConfig, validatorConfig, authService, arithService, amendmentService, dateService, formatService) {
		var ctrl = this, params = $scope.$stateParams.params, errorMessage = {};
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.amendment = {};
		ctrl.actionName = "amendmentLog";

		ctrl.init = function() {
			/** ***************Past Due****************** */
			if (ctrl.validatorConfig)
				ctrl.layoutConfig.formConfigs.pastdueNew.tableConfigs.table.validatorConfig = ctrl.validatorConfig.pastdueSchdNewList;
			ctrl.pastdueSchdNewListGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.pastdueNew.tableConfigs.table, function(eventRow, selectedRows) {
				ctrl.selectedPastdues = selectedRows;
			});
			ctrl.pastdueSchdNewListGridOptions.data = "vm.amendment.pastdueSchdNewList";
			ctrl.pastdueSchdNewListGridOptions.filterRowOperation = function(row, type) {
				if (row && row.entity && (row.entity.readonlyFlag) && (type == "remove")) {
					return true;
				} else {
					return false;
				}
			};
			ctrl.pastdueSchdOldListGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.pastdueOld.tableConfigs.table, null);
			ctrl.pastdueSchdOldListGridOptions.data = "vm.amendment.pastdueSchdOldList";
			/** ***************Past Due****************** */

			/** ***************interest****************** */
			ctrl.intSchdNewListGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.intSchdNew.tableConfigs.table, null);
			ctrl.intSchdNewListGridOptions.data = "vm.amendment.intSchdNewList";

			ctrl.intSchdNewListGridOptions.filterRowOperation = function(row, type) {
				if ((!ctrl.amendment.loan.loanInt.spreadTierType2 || ctrl.amendment.loan.loanInt.spreadTierType2 == "N")
						&& (!ctrl.amendment.loan.loanInt.spreadTierType || ctrl.amendment.loan.loanInt.spreadTierType == "N")) {
					return true;
				} else if (row && row.entity && (row.entity.hasFrontSameCriteria == "Y" || row.entity.pastDueFlag) && (type == "add")) {
					return true;
				} else if (row && row.entity && (row.entity.pastDueFlag) && (type == "remove")) {
					return true;
				} else {
					return false;
				}
			};

			ctrl.intSchdOldListGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.intSchdOld.tableConfigs.table, null);
			ctrl.intSchdOldListGridOptions.data = "vm.amendment.intSchdOldList";
			/** ***************interest****************** */
			amendmentService.initDataOptions().then(function(response) {
				return $q(function(resolved, rejected) {
					ctrl.countryOptions = response.country;
					ctrl.spreadTierTypeOptions = response.spreadTierType;
					resolved();
				});
			}).then(function() {
				ctrl.initTabs();
			});
		};

		/** ***************Past Due****************** */
		ctrl.addRow = function(row) {
			return $q(function(resolved, rejected) {
				var pastdueTenorFrom;
				if (ctrl.amendment.pastdueSchdNewList && ctrl.amendment.pastdueSchdNewList.length > 0) {
					var prePastdueTenor = ctrl.amendment.pastdueSchdNewList[ctrl.amendment.pastdueSchdNewList.length - 1].pastdueTenor;
					if (!prePastdueTenor) {
						modalService.openErrorDialogs({
							messages : [ "The To n-th Day must be not null!" ]
						});
						rejected();
						return;
					}
					pastdueTenorFrom = arithService.add(prePastdueTenor, 1);
				} else {
					pastdueTenorFrom = 1;
				}
				row.pastdueTenorFrom = pastdueTenorFrom;
				resolved();
			});
		};

		ctrl.removePastdueRow = function(row) {
			// reset pastdueTenorFrom
			var pastdueTenorFrom = 1;
			angular.forEach(ctrl.amendment.pastdueSchdNewList, function(pastdue, index) {
				pastdue.pastdueTenorFrom = pastdueTenorFrom;
				if(pastdue.pastdueTenor){					
					pastdueTenorFrom = arithService.add(formatService.parseNumber(pastdue.pastdueTenor), 1);
				}
			});
		};

		ctrl.pastdueTenorChanged = function(rowObj) {
			amendmentService.pastdueTenorChanged(ctrl.amendment.pastdueSchdNewList, rowObj);
		};

		ctrl.pastdueGraceChanged = function(rowObj) {
			amendmentService.pastdueGraceChanged(ctrl.amendment.pastdueSchdNewList, rowObj);
		};

		ctrl.pastdueTenorOldChanged = function(rowObj) {
			amendmentService.pastdueTenorChanged(ctrl.amendment.pastdueSchdOldList, rowObj);
		};

		ctrl.pastdueGraceOldChanged = function(rowObj) {
			amendmentService.pastdueGraceChanged(ctrl.amendment.pastdueSchdOldList, rowObj);
		};
		
		/** ***************Past Due****************** */
		/** ***************interest****************** */
		ctrl.baseRateNewChanged = function(amendment) {
			amendmentService.baseRateNewChanged(amendment);
		};
		
		ctrl.totalSpreadRateNewChanged = function(amendment) {
			amendmentService.totalSpreadRateNewChanged(amendment);
		};
		
		ctrl.spreadRateNewChanged = function(amendment) {
			amendmentService.spreadRateNewChanged(amendment);
		};

		ctrl.baseRateOldChanged = function(amendment) {
			amendmentService.baseRateOldChanged(amendment);
		};
		
		ctrl.totalSpreadRateOldChanged = function(amendment) {
			amendmentService.totalSpreadRateOldChanged(amendment);
		};
		
		ctrl.spreadRateOldChanged = function(amendment) {
			amendmentService.spreadRateOldChanged(amendment);
		};
		/** ***************interest****************** */

		ctrl.obligorCodeNew = function(amendment, form, firstLoad) {
			if (firstLoad) {
				return;
			}
			amendmentService.obligorCodeNew(amendment);
		};

		ctrl.save = function() {
			var messages = [];
			angular.forEach(errorMessage, function(field) {
				angular.forEach(field, function(rule) {
					messages.push(rule);
				});
			});
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			} else if (!amendmentService.resetUFlag(ctrl.amendment)) {
				modalService.openErrorDialogs({
					"messages" : [ "title.dialogs.info.loanamd.nochanged" ]
				});
			} else {
				// must after resetUFlag
				amendmentService.validateBilling(ctrl.amendment, messages);
				if (messages.length > 0) {
					modalService.openErrorDialogs({
						"messages" : messages
					});
				}
				return authService.logSubmitted(ctrl.amendment).then(submitSuccessful, submitFailed);
			}
		};

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				"messages" : [ "title.dialog.successful.submit" ],
				"btnCallback" : {
					"close" : function() {
						$scope.go("cls.workflow.wfTxn.list");
					}
				},
				"redirections" : [ {
					"name" : "title.infobar.workflow.list",
					"state" : "cls.workflow.wfTxn.list",
					"params" : {}
				} ]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				"messages" : response.error
			});
		}

		function selectLoanId(param) {
			if (!param || param.length == 0) {
				modalService.openErrorDialogs({
					messages : [ "title.dialogs.info.norecsel" ]
				});
				return false;
			}
			authService.logInit(ctrl.amendment).then(function(response) {
				ctrl.actionName = "amendmentCreateInit";
				var amendment = response.data;
				amendment.pastdueSchdNewList = amendment.pastdueSchdNewList || [];
				amendment.intSchdNewList = amendment.intSchdNewList || [];
				amendmentService.resetIntSchdList(amendment, ctrl.intSchdNewListGridOptions, ctrl.intSchdOldListGridOptions);
				amendmentService.processPastDue(amendment, ctrl.intSchdNewListGridOptions);
				amendmentService.setpastDueSchdDate(amendment);
				// loan interest is prepaid, interest radio is No and readonly
				if (amendment.loan.loanInt.intCollMethod == "P") {
					amendment.interestFlag = "N";
				}
				// amendment.loan.loanExt.lastPayDate > amendment.amdDate, then princAmtChg will be readonly
				var lastPayDate, amdDate = amendment.amdDate;
				if (amendment.loan && amendment.loan.loanExt && amendment.loan.loanExt.lastPayDate) {
					lastPayDate = amendment.loan.loanExt.lastPayDate;
				}
				if (lastPayDate && amdDate && dateService.compareDate(amdDate, lastPayDate) > 0) {// lastPayDate>amdDate
					ctrl.princAmtChgReadonly = "Y";
				} else {
					ctrl.princAmtChgReadonly = "N";
				}
				amendmentService.resetPastdueSchdList(amendment);
				// pastdueReadonlyFlag
				if (amendment.loan.loanInfo.loanStatus == "P" && (!amendment.pastdueSchdNewList || amendment.pastdueSchdNewList.length == 0)) {
					ctrl.pastdueReadonlyFlag = "Y";
				} else {
					ctrl.pastdueReadonlyFlag = "N";
				}
				ctrl.amendment = amendment;
				ctrl.princAmtChgChanged(ctrl.amendment);
				ctrl.layoutConfig = layoutConfig;
			}, submitFailed);
			$scope.disableUnloadCheck();
		}

		ctrl.princAmtChgChanged = function(amendment, form, firstLoad) {
			if (firstLoad) {
				return;
			}
			amendmentService.princAmtChgChanged(amendment);
		};

		ctrl.loanIdLookUp = {
			"id" : "cls.lookupTxnRefList",
			"params" : {
				"loanNo" : "<loanNo",
				"lockFlag" : "N",
				"loanStatusList" : [ "N", "P", "Q" ]
			},
			"boundTo" : {
				"loanId" : "loanId"
			},
			"callback" : {
				"ok" : selectLoanId
			},
			"okEvent" : true,
			"cancelEvent" : false
		};

		/** *****************interest********************* */
		ctrl.addIntSchd = function(row) {
			row.hasFrontSameCriteria = "N";
		};

		ctrl.removeIntSchdRow = function(row) {
			amendmentService.resetSpreadTierShow(row.entity, ctrl.amendment.intSchdNewList);
		};

		ctrl.addSubRow = function(row) {
			var _selectedTierCriteria;
			var _selectedTierCriteriaIndex;
			var selectedNum = 0;
			angular.forEach(ctrl.amendment.intSchdNewList, function(spreadTier, index) {
				if (spreadTier.$$hashKey == row.entity.$$hashKey) {
					_selectedTierCriteria = spreadTier;
					_selectedTierCriteriaIndex = index;
					selectedNum = selectedNum + 1;
				}
			});

			var newTierCriteria = {};
			newTierCriteria.hasFrontSameCriteria = "Y";
			newTierCriteria.criteria = _selectedTierCriteria.criteria;
			ctrl.amendment.intSchdNewList.splice(_selectedTierCriteriaIndex + 1, 0, newTierCriteria);
		};

		ctrl.spreadTierValueChanged = function(param, form, firstLoad) {
		};

		ctrl.criteriaChanged = function(currTierCriteria, form, firstLoad) {
		};

		/** *****************interest********************* */

		/** *****************billing********************* */
		ctrl.billFirstOnNewChanged = function(amendment, form, firstLoad) {
			if (firstLoad) {
				return;
			}
			amendmentService.setBillFirstOnNew(amendment);
		};
		ctrl.billOnEomNewChanged = function(amendment, form, firstLoad) {
			if (firstLoad) {
				return;
			}
			amendmentService.setBillFirstOnNew(amendment);
		};

		ctrl.billFreqTypeNewChanged = function(amendment, form, firstLoad) {
			if (firstLoad) {
				return;
			}
			amendmentService.setBillFirstOnNew(amendment);
		};

		/** *****************billing********************* */
		ctrl.initTabs = function() {
			amendmentService.resetNewOld(ctrl.amendment);
			ctrl.tabsetIndex = amendmentService.initTabs(ctrl.amendment);
		};
	}
})(angular);
